import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/coustom_outline_button.dart';
import 'package:casdon/common/widget/gradient_button.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/shared_preferences_utils.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/core/utils/wifi/wifi_utils.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

@RoutePage()
class PairnetFailedScreen extends ConsumerWidget {
  final String? pid;
  final String? deviceName;
  final bool? isQrPairNet;

  const PairnetFailedScreen({
    super.key,
    this.pid,
    this.deviceName,
    this.isQrPairNet,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(
        title: '添加设备',
        onBack: () {
          // 回到首页
          _goHomePage(context);
        },
      ),
      body: Column(
        children: [
          _buildSuccessHeader(context),
          _buildSureInfo(context),
          const Spacer(),
          _buildActionButtons(context),
          SizedBox(height: 155.h),
        ],
      ),
    );
  }

  Widget _buildSuccessHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 40.h),
      child: Column(
        children: [
          Container(
            width: 48.w,
            height: 48.w,
            decoration: BoxDecoration(
              color: const Color(0xFFD54941),
              shape: BoxShape.circle,
            ),
            child: Icon(Icons.check, color: Colors.white, size: 30.w),
          ),
          SizedBox(height: 16.h),
          Text(
            '添加设备失败',
            style: context.textTheme.headlineLarge?.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSureInfo(BuildContext context) {
    return Expanded(
      // ✅ Expanded 应该放在 Column 的同级
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 24.w),
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '确认设备已重置，灯在快闪检查 Wi-Fi 是否为 2.4GHz核对 Wi-Fi 密码是否正确',
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.customColorThemeNonNull.textColor3,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildActionButtons(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: Row(
        children: [
          Expanded(
            child: CustomOutlineButton(
              onPressed: () => _goHomePage(context),
              text: '回到首页',
              borderColor: context.colorScheme.primary,
              borderRadius: 24,
            ),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: GradientButton(
              text: '重试',
              borderRadius: 24,
              onPressed: () => _retry(context),
            ),
          ),
        ],
      ),
    );
  }

  void _goHomePage(BuildContext context) {
    context.router.popUntilRouteWithName(TabRoute.name);
  }

  Future<void> _retry(BuildContext context) async {
    if (!context.mounted) return; // ✅ 提前检查一次
    if (isQrPairNet == true) {
      context.router.popUntil((route) {
        return route.settings.name == QRScannerRoute.name;
      });
      return;
    }
    if (pid == null || deviceName == null) return;
    try {
      final ssidResult =
          await WifiUtils.getInstance().getCurrentWifiSsidResult();
      if (!ssidResult.hasPermission) {
        ToastUtil.show("请开启定位权限后再尝试");
        return;
      }
      final ssid = ssidResult.ssid;
      if (ssid == null) {
        Log.i('当前未连接WiFi，进入WiFi配置页面');
        if (!context.mounted) return;

        context.router.replace(
          WifiConfigRoute(
            pid: pid!,
            deviceName: deviceName!,
            nextRoute: "add_device_progress",
          ),
        );
        return;
      }

      final spUnit = await SPUtils.getInstance();
      final pwd = spUnit.getString(ssid);

      if (pwd.isEmpty) {
        Log.i('当前WiFi SSID: $ssid, 未存储密码，进入WiFi配置页面');
        if (!context.mounted) return;
        context.router.replace(
          WifiConfigRoute(
            pid: pid!,
            deviceName: deviceName!,
            nextRoute: "add_device_progress",
          ),
        );
        return;
      }

      Log.i('当前WiFi SSID: $ssid, 已存储密码，直接进入配网进度页面');
      if (!context.mounted) return;
      AddDeviceProgressRoute(
        pid: pid!,
        ssid: ssid,
        pwd: pwd,
        deviceName: deviceName!,
        virtualId: null,
      ).push(context);
    } catch (e, stack) {
      Log.e('点击重试出错', e, stack);
    }
  }

  bool _popToRouteIfExists(
    BuildContext context,
    bool Function(Route<dynamic> settings) matcher,
  ) {
    bool found = false;
    Navigator.of(context).popUntil((route) {
      if (matcher(route)) {
        found = true;
        return true;
      }
      return false;
    });
    return found;
  }
}
